const express = require('express')
const path = require('path')
const request = require('request')
const config = require('./config')
const bodyParser = require('body-parser')

const app = express()

//配置static中间件
// app.use(express.static(path.join(__dirname, 'public')))

//配置bodyParser中间件
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

// cors跨域请求头设置
app.use(function (req,res,next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next()
})

app.get('/api/movieListData', (req, res, next) => {
	const message = JSON.parse(req.query.message)
	const url=`${config.DOUBAN_IN_THEATERS}${message.movieType}?start=${message.start}&count=${message.count}`
	request(url, function (error, response, body) {
		if (!error) {
			res.send( body )
		}
	})
})

app.get('/api/movieDetailData', (req, res, next) => {
	const id = req.query.message
	const url=`${config.DOUBAN_IN_THEATERS}subject/${id}`
	request(url, function (error, response, body) {
		if (!error) {
			res.send( body )
		}
	})
})

app.get('/api/movieSearchData', (req, res, next) => {
	const message = JSON.parse(req.query.message)
	const keyword = encodeURI(message.keyword)
	const url=`${config.DOUBAN_IN_THEATERS}search?q=${keyword}&start=${message.start}&count=${message.count}`
	request(url, function (error, response, body) {
		if (!error) {
			res.send( body )
		}
	})
})

app.post('/api/feedbackData', (req, res, next) => {
	const message = JSON.parse( req.body.message )
	res.send({
		status: 'OK'
	})
})

//渲染index.html文件
app.get('*', (req, res, next) => {
	// 注意: 这里使用sendFile渲染
    res.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})


app.listen(config.PORT, config.HOST, () => {
	console.log(`service is running at ${config.HOST}:${config.PORT}`)
})